# 转换停车标志

# 导入所需包
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# 导入图片
img = mpimg.imread('perspective_transform/perspective_transform.jpg')

plt.imshow(img)
plt.show()

# 分别定义四个点 (78, 52) (78, 78) (21, 41) (22, 71)
plt.imshow(img)
plt.plot(78, 52, '.') # 右上角
plt.plot(78, 78, '.') # 右下角
plt.plot(21, 41, '.') # 左上角
plt.plot(22, 71, '.') # 左下角
plt.show()

def warp(img):
    img_size = (img.shape[1], img.shape[0])

    # src = np.float32(
    #        [[78, 52],
    #         [78, 78],
    #         [21, 41],
    #         [22, 71]])

    # dst = np.float32(
    #        [[70, 45],
    #         [70, 75],
    #         [20, 40],
    #         [20, 70]])

    src = np.float32(
            [[21,40],
             [21,68],
             [78,76],
             [78,50]])
    
    dst = np.float32(
            [[21,45],
             [21,70],
             [65,70],
             [65,45]])

    # 计算透视变换
    M = cv2.getPerspectiveTransform(src, dst)

    Minv = cv2.getPerspectiveTransform(dst, src)

    warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)

    return warped

warped_im = warp(img)
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))

ax1.set_title('Source image')
ax1.imshow(img)

ax2.set_title('Warped image')
ax2.imshow(warped_im)

plt.show()

r, g, b = cv2.split(warped_im)
result = cv2.merge((b, g, r))

cv2.imwrite("perspective_transform/output_perspective_transform.jpg", result)